/*
 * @Author: Lin Hongwei
 * @Date: 2022-09-08 22:53:45
 * @LastEditTime: 2022-09-20 20:35:16
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 自定义hook文件
 */

import { useState, useEffect, useRef } from "react";

/**
 * @description: 自定义mounted挂载生命钩子Hook
 * 自定义hook需要以use开头
 */
export const useMount = (callback: () => void) => {
  //监听[]，将只初始化的时候执行一次
  useEffect(() => {
    callback && callback();
  }, []);
};

/**
 * @description: 防抖函数
 * @return {*} 当前面的定时器清除后再创建新的
 */
// export const debounce = (func,delay)=>{
//   let timer = null;
//   return ()=>{
//     if(timer){
//       clearTimeout(timer);
//     }
//     timer = setTimeout(()=>{
//       func&&func();
//     },delay)
//   }
// }
// let log = debounce(()=>console.log("1"),1000);
// log();
// log();
// log();

export const useDebouce = <T>(value: T, delay?: number) => {
  //useState在第二次调用的时候直接返回当前的state
  const [debounceValue, setDebounceValue] = useState(value);
  useEffect(() => {
    let timer = setTimeout(() => setDebounceValue(value), delay);
    //在每次执行useEffect的时候都会调用该函数清除上一个effect
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debounceValue;
};

/**
 * @description: 头部标题
 * @param {string} title - 标题
 * @param {boolean} isUp - 是否保持title
 */
export const useDocumentTitle = (title: string, isUp: boolean = true) => {
  // const oldTitle = document.title;
  const oldTitle = useRef(document.title).current;
  useEffect(() => {
    document.title = title;
  }, [title]);
  useEffect(() => {
    return () => {
      if (!isUp) {
        document.title = oldTitle;
      }
    };
  }, []);
};

/**
 * @description: 组件的挂载状态
 * @return 挂载为true，卸载为false
 */
export const useMountedStateRef = () => {
  const montedStateRef = useRef(false);
  useEffect(() => {
    montedStateRef.current = true;
    return () => {
      montedStateRef.current = false;
    };
  });
  return montedStateRef;
};
